import json
import os


class ConfigManager:
    def __init__(self):
        self.config_path = 'config.json'
        self.config = self._load_config()

    def _load_config(self):
        if not os.path.exists(self.config_path):
            return {'programs': [], }
        
        try:
            with open(self.config_path, 'r') as f:
                config = json.load(f)
        except (json.JSONDecodeError, IOError):
            os.remove(self.config_path)
            return {'programs': []}
        
        # 迁移旧配置
        for program in config.get('programs', []):
            if 'name' not in program:
                program['name'] = os.path.splitext(os.path.basename(program['path']))[0]
        return config

    def save_config(self):
        with open(self.config_path, 'w') as f:
            json.dump(self.config, f, indent=2)

    def add_program(self, name, path, time_limit, terminate_processes):
        self.config['programs'].append({
            'name': name,
            'path': path,
            'time_limit': time_limit,
            'last_launch_date': None,
            'terminate_processes': terminate_processes
        })
        self.save_config()

    def remove_program(self, index):
        if 0 <= index < len(self.config['programs']):
            del self.config['programs'][index]
            self.save_config()

    def get_programs(self):
        return self.config['programs']